# Computations
import numpy as np
import pandas as pd
# sklearn
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, cross_val_score, KFold, StratifiedShuffleSplit
from sklearn import metrics
from sklearn.feature_selection import RFE
from sklearn.neural_network import MLPClassifier
# Visualisation libraries
## Text
from colorama import Fore, Back, Style
from IPython.display import Image, display, Markdown, Latex, clear_output
## progressbar
import progressbar
## plotly
from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go
import plotly.offline as py
from plotly.subplots import make_subplots
import plotly.express as px
## seaborn
import seaborn as sns
## matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
from matplotlib.font_manager import FontProperties
import matplotlib.colors as mcolors
plt.style.use('seaborn-whitegrid')
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
plt.rcParams['text.color'] = 'k'
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
Anomaly detection is a classification process in which rare items, events, or observations in data sets are identified. Learn more about this here. In this article, we investigate Credit Card Fraud Detection dataset from Kaggle.com.
Credit card companies must be able to recognize fraudulent credit card transactions so that customers are not charged for items that they did not purchase.
The datasets contain transactions made by credit cards in September 2013 by European cardholders. This dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions. The dataset is highly unbalanced, the positive class (frauds) account for 0.172% of all transactions. It contains only numerical input variables which are the result of a PCA transformation. Unfortunately, due to confidentiality issues, we cannot provide the original features and more background information about the data. Features V1, V2, … V28 are the principal components obtained with PCA, the only features which have not been transformed with PCA are 'Time' and 'Amount'. Feature 'Time' contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature 'Amount' is the transaction Amount, this feature can be used for example-dependant cost-sensitive learning. Feature 'Class' is the response variable and it takes value 1 in case of fraud and 0 otherwise.
Path ='Data/creditcard.csv'
Data = pd.read_csv(Path, sep=',')
Labels = ['Normal', 'Fraud']
Target = 'Class'
Col = []
# Temp = re.findall("(\d+)", s)
for s in Data.columns:
if any(map(str.isdigit, s)) == True:
Temp = s.split('V')
Col.append('V'+ Temp[-1].zfill(2))
else:
Col.append(s)
Data.columns = Col
del Col
display(pd.DataFrame(Data.shape, columns = ['Count'], index = ['Attributes', 'Instances']).T)
def Data_info(Inp, Only_NaN = False):
Out = Inp.dtypes.to_frame(name='Data Type').sort_values(by=['Data Type'])
Out = Out.join(Inp.isnull().sum().to_frame(name = 'Number of NaN Values'), how='outer')
Out ['Size'] = Inp.shape[0]
Out['Percentage'] = 100 - np.round(100*(Out['Number of NaN Values']/Inp.shape[0]),2)
Out.index.name = 'Features'
Out['Data Type'] = Out['Data Type'].astype(str)
if Only_NaN:
Out = Out.loc[Out['Number of NaN Values']>0]
return Out
data_info = Data_info(Data).reset_index(drop = False)
fig = px.bar(data_info, x= 'Features', y= 'Percentage', color = 'Data Type', text = 'Data Type',
color_discrete_sequence = ['PaleGreen', 'LightBlue', 'PeachPuff'], hover_data = data_info.columns)
fig.update_layout(plot_bgcolor= 'white', legend=dict(x=1, y=.5, traceorder="normal",
bordercolor="DarkGray", borderwidth=1), height = 400, width = 980)
fig.update_traces(texttemplate= 6*' ' + '%{label}', textposition='inside')
fig.update_traces(marker_line_color= 'Black', marker_line_width=1., opacity=1)
fig.show()
| Attributes | Instances | |
|---|---|---|
| Count | 284807 | 31 |
fig, ax = plt.subplots(1, 1, figsize=(16, 6))
_ = ax.hist(Data.loc[Data.Class == 0, 'Amount'], 100, color = '#34495e', hatch = '/', lw = 1.5,
edgecolor = '#3498db', label = Labels[0])
_ = ax.hist(Data.loc[Data.Class == 1, 'Amount'], 10, Color = '#e74c3c', hatch = '\\', lw = 1.5,
edgecolor = 'DarkRed', label = Labels[1])
_ = ax.set_xlabel('Amount')
_ = ax.set_ylabel('Frequency (Logarithm Scale)')
_ = ax.set_xlim([0, 2e4])
_ = ax.set_yscale('log')
_ = ax.set_ylim([0, 1e6])
_ = ax.legend(bbox_to_anchor=(1, 1), fontsize=14, ncol=2)
fig, ax = plt.subplots(1, 1, figsize=(16, 6))
_ = ax.scatter(Data.loc[Data.Class == 0, 'Time'], Data.loc[Data.Class == 0, 'Amount'], s= 30,
facecolors='SkyBlue', edgecolors='MidnightBlue', alpha = 0.8, label = Labels[0])
_ = ax.scatter(Data.loc[Data.Class == 1, 'Time'], Data.loc[Data.Class == 1, 'Amount'], s= 30,
facecolors='Orange', edgecolors='DarkRed', alpha = 1, label = Labels[1])
_ = ax.set_xlabel('Time (in seconds)')
_ = ax.set_ylabel('Amount')
_ = ax.set_xlim([-500, Data.Time.max()+500])
_ = ax.set_ylim([-250, 2e4])
_ = ax.legend(bbox_to_anchor=(1, 1), fontsize=14, ncol=2)
Let's look that transaction class distribution
def Dist_Table(Inp = Data, Target = Target):
Table = Inp[Target].value_counts().to_frame('Count').reset_index(drop = False).rename(columns = {'index':Target})
Table[Target] = Table[Target].replace(dict(zip([0,1],Labels)))
Table['Percentage'] = np.round(100*(Table['Count']/Table['Count'].sum()),2)
return Table
Table = Dist_Table()
def Dist_Plot(Table, PieColors = ['SeaGreen', 'FireBrick'], TableColors = ['Navy','White']):
fig = make_subplots(rows=1, cols=2, horizontal_spacing = 0.02, column_widths=[0.6, 0.4],
specs=[[{"type": "table"},{"type": "pie"}]])
# Right
fig.add_trace(go.Pie(labels=Table[Target].values, values=Table['Count'].values, pull=[0, 0.1], textfont=dict(size=16),
marker=dict(colors = PieColors, line=dict(color='black', width=1))), row=1, col=2)
fig.update_traces(hole=.5)
fig.update_layout(height = 400, legend=dict(orientation="v"), legend_title_text= Target,
annotations=[dict(text= '<b>' + Target + '<b>', x=0.835, y=0.5, font_size=14, showarrow=False)])
# Left
T = Table.copy()
T['Percentage'] = T['Percentage'].map(lambda x: '%% %.2f' % x)
Temp = []
for i in T.columns:
Temp.append(T.loc[:,i].values)
fig.add_trace(go.Table(header=dict(values = list(Table.columns), line_color='darkslategray',
fill_color= TableColors[0], align=['center','center'],
font=dict(color='white', size=12), height=25), columnwidth = [0.2, 0.2, 0.2],
cells=dict(values=Temp, line_color='darkslategray',
fill=dict(color= [TableColors[1], TableColors[1]]),
align=['center', 'center'], font_size=12, height=20)), 1, 1)
fig.update_layout(title={'text': '<b>' + Target + 'Distribution' + '<b>', 'x':0.5,
'y':0.90, 'xanchor': 'center', 'yanchor': 'top'})
fig.show()
Dist_Plot(Table)
The Dataset is quite large, we would like to use pandas DataFrame sample feature with using a one-tenth of the data as a sample.
df= Data.sample(frac = 0.1, random_state=1).reset_index(drop = True)
Dist_Plot(Dist_Table(df), PieColors = ['CornflowerBlue', 'OrangeRed'], TableColors = ['Purple','Lavenderblush'])
First off, let's define $X$ and $y$ sets.
X = df.drop(columns = [Target])
y = df[Target]
Moreover, high variance for some features can hurt our modeling process. For this reason, we would like to standardize features by removing the mean and scaling to unit variance. In this article, we demonstrated the benefits of scaling data using StandardScaler().
# scaling data
scaler = preprocessing.StandardScaler()
X_std = scaler.fit_transform(X)
X_std = pd.DataFrame(data = X_std, columns =X.columns)
del scaler
fig, ax = plt.subplots(2, 1, figsize=(18, 8))
ax = ax.ravel()
font = FontProperties()
font.set_weight('bold')
CP = [sns.color_palette("OrRd", 20), sns.color_palette("Greens", 20)]
Names = ['Variance of the Features', 'Variance of the Features (Standardized)']
Sets = [X, X_std]
kws = dict(label='Feature\nVariance', aspect=20, shrink= .3)
for i in range(len(ax)):
Temp = Sets[i].var().sort_values(ascending = False).to_frame(name= 'Variance').round(2).T
_ = sns.heatmap(Temp, ax=ax[i], annot=True, square=True, cmap = CP[i],
linewidths = 0.8, vmin=0, vmax=Temp.max(axis =1)[0], annot_kws={"size": 6},
cbar_kws=kws)
_ = ax[i].set_yticklabels('')
_ = ax[i].set_title(Names[i], fontproperties=font, fontsize = 16)
del Temp
X = X_std.copy()
del CP, Names, ax, fig, font, Sets, kws,
fig, ax = plt.subplots(figsize=(17,20))
Temp = pd.concat([X, y], axis = 1)
Temp = Temp.corr().round(2)
Temp = Temp.loc[(Temp.index == Target)].drop(columns = Target).T.sort_values(by = Target).T
_ = sns.heatmap(Temp, ax=ax, annot=True, square=True, cmap =sns.color_palette("Greens", n_colors=10),
linewidths = 0.8, vmin=0, vmax=1,
annot_kws={"size": 12},
cbar_kws={'label': Target + ' Correlation', "aspect":40, "shrink": .4, "orientation": "horizontal"})
_ = ax.set_yticklabels('')
del Temp
Modifying dataset.
df[X.columns.tolist()] = X_std[X.columns.tolist()]
df.to_csv (Path.split(".")[0]+'_STD.csv', index = None, header=True)
StratifiedKFold is a variation of k-fold which returns stratified folds: each set contains approximately the same percentage of samples of each target class as the complete set.
Test_Size = 0.3
sss = StratifiedShuffleSplit(n_splits=1, test_size=Test_Size, random_state=42)
_ = sss.get_n_splits(X, y)
for train_index, test_index in sss.split(X, y):
X_train, X_test = X.loc[train_index], X.loc[test_index]
y_train, y_test = y[train_index], y[test_index]
del sss
Colors = ['SeaGreen', 'FireBrick']
nc = 2
fig = make_subplots(rows=1, cols=nc, specs=[[{'type':'domain'}]*nc])
fig.add_trace(go.Pie(labels=Labels,
values=y_train.value_counts().values,
pull=[0, 0.1],
name= 'Train Set',
textfont=dict(size=16),
marker= dict(colors = Colors, line=dict(color='black', width=1))), 1, 1)
fig.add_trace(go.Pie(labels=Labels,
values=y_test.value_counts().values,
pull=[0, 0.1],
name= 'Test Set',
textfont=dict(size=16),
marker= dict(colors = Colors, line=dict(color='black', width=1))), 1, 2)
fig.update_traces(hole=.5)
fig.update_layout(height = 400, legend=dict(orientation="v"),
legend_title_text= Target,
annotations=[dict(text= '<b>' + 'Train<br>Set' + '<b>', x=0.195, y=0.5, font_size=14, showarrow=False),
dict(text= '<b>' + 'Test<br>Set' + '<b>', x=0.8, y=0.5, font_size=14, showarrow=False)],
title={'text': '<b>' + Target + '<b>', 'x':0.48, 'y': .83, 'xanchor': 'center', 'yanchor': 'top'})
fig.show()
This model optimizes the log-loss function using LBFGS or stochastic gradient descent. See sklearn.neural_network.MLPClassifier.
def Header(Text, L = 100, C = 'Blue', T = 'White'):
BACK = {'Black': Back.BLACK, 'Red':Back.RED, 'Green':Back.GREEN, 'Yellow': Back.YELLOW, 'Blue': Back.BLUE,
'Magenta':Back.MAGENTA, 'Cyan': Back.CYAN}
FORE = {'Black': Fore.BLACK, 'Red':Fore.RED, 'Green':Fore.GREEN, 'Yellow':Fore.YELLOW, 'Blue':Fore.BLUE,
'Magenta':Fore.MAGENTA, 'Cyan':Fore.CYAN, 'White': Fore.WHITE}
print(BACK[C] + FORE[T] + Style.NORMAL + Text + Style.RESET_ALL + ' ' + FORE[C] +
Style.NORMAL + (L- len(Text) - 1)*'=' + Style.RESET_ALL)
def Line(L=100, C = 'Blue'):
FORE = {'Black': Fore.BLACK, 'Red':Fore.RED, 'Green':Fore.GREEN, 'Yellow':Fore.YELLOW, 'Blue':Fore.BLUE,
'Magenta':Fore.MAGENTA, 'Cyan':Fore.CYAN, 'White': Fore.WHITE}
print(FORE[C] + Style.NORMAL + L*'=' + Style.RESET_ALL)
def Search_List(Key, List): return [s for s in List if Key in s]
def Best_Parm(model, param_dist, Top = None, X = X, y = y, n_splits = 20, scoring = 'precision', H = 600, titleY = .95):
grid = RandomizedSearchCV(estimator = model, param_distributions = param_dist,
cv = StratifiedShuffleSplit(n_splits=n_splits, test_size=Test_Size, random_state=42),
n_iter = int(1e3), scoring = scoring, error_score = 0, verbose = 0,
n_jobs = 10, return_train_score = True)
_ = grid.fit(X, y)
Table = Grid_Table(grid)
if Top == None:
Top = Table.shape[0]
Table = Table.iloc[:Top,:]
# Table
T = Table.copy()
T['Train Score'] = T['Mean Train Score'].map(lambda x: ('%.2e' % x))+ ' ± ' +T['STD Train Score'].map(lambda x: ('%.2e' % x))
T['Test Score'] = T['Mean Test Score'].map(lambda x: ('%.2e' % x))+ ' ± ' +T['STD Test Score'].map(lambda x: ('%.2e' % x))
T['Fit Time'] = T['Mean Fit Time'].map(lambda x: ('%.2e' % x))+ ' ± ' +T['STD Fit Time'].map(lambda x: ('%.2e' % x))
T = T.drop(columns = ['Mean Train Score','STD Train Score','Mean Test Score','STD Test Score','Mean Fit Time','STD Fit Time'])
display(T.head(Top).style.hide_index().background_gradient(subset= ['Rank Test Score'],
cmap=sns.diverging_palette(145, 300, s=60, as_cmap=True)).\
set_properties(subset=['Params'], **{'background-color': 'Indigo', 'color': 'White'}).\
set_properties(subset=['Train Score'], **{'background-color': 'HoneyDew', 'color': 'Black'}).\
set_properties(subset=['Test Score'], **{'background-color': 'Azure', 'color': 'Black'}).\
set_properties(subset=['Fit Time'], **{'background-color': 'Linen', 'color': 'Black'}))
# Plot
Grid_Performance_Plot(Table, n_splits = n_splits, H = H, titleY = titleY)
return grid
def Grid_Table(grid):
Table = pd.DataFrame({'Rank Test Score': grid.cv_results_['rank_test_score'],
'Params':[str(s).replace('{', '').replace('}', '').\
replace("'", '') for s in grid.cv_results_['params']],
# Train
'Mean Train Score': grid.cv_results_['mean_train_score'],
'STD Train Score': grid.cv_results_['std_train_score'],
# Test
'Mean Test Score': grid.cv_results_['mean_test_score'],
'STD Test Score': grid.cv_results_['std_test_score'],
# Fit time
'Mean Fit Time': grid.cv_results_['mean_fit_time'],
'STD Fit Time': grid.cv_results_['std_fit_time']})
Table = Table.sort_values('Rank Test Score').reset_index(drop = True)
return Table
def Grid_Performance_Plot(Table, n_splits, H = 550, titleY =.95):
Temp = Table['Mean Train Score']-Table['STD Train Score']
Temp = np.append(Temp, Table['Mean Test Score']-Table['STD Test Score'])
L = np.floor((Temp*100- Temp)).min()/100
Temp = Table['Mean Train Score']+Table['STD Train Score']
Temp = np.append(Temp, Table['Mean Test Score']+Table['STD Test Score'])
R = np.ceil((Temp*100 + Temp)).max()/100
fig = make_subplots(rows=1, cols=2, horizontal_spacing = 0.02, shared_yaxes=True,
subplot_titles=('<b>' + 'Train Set' + '<b>', '<b>' + 'Test Set' + '<b>'))
fig.add_trace(go.Scatter(x= Table['Params'], y= Table['Mean Train Score'], showlegend=False, marker_color= 'SeaGreen',
error_y=dict(type='data',array=Table['STD Train Score'], visible=True)), 1, 1)
fig.add_trace(go.Scatter(x= Table['Params'], y= Table['Mean Test Score'], showlegend=False, marker_color= 'RoyalBlue',
error_y=dict(type='data',array= Table['STD Test Score'], visible=True)), 1, 2)
fig.update_xaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
zeroline=False, zerolinewidth=1, zerolinecolor='Black',
showgrid=False, gridwidth=1, gridcolor='Lightgray')
fig.update_yaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
zeroline=True, zerolinewidth=1, zerolinecolor='Black',
showgrid=True, gridwidth=1, gridcolor='Lightgray', range= [L, R])
fig.update_yaxes(title_text="Mean Score", row=1, col=1)
fig.update_layout(plot_bgcolor= 'white', width = 980, height = H,
title={'text': '<b>' + 'RandomizedSearchCV with %i-fold cross validation' % n_splits + '<b>',
'x':0.5, 'y':titleY, 'xanchor': 'center', 'yanchor': 'top'})
fig.show()
def Stratified_CV_Scoring(model, X = X, y = y, n_splits = 10):
sss = StratifiedShuffleSplit(n_splits = n_splits, test_size=Test_Size, random_state=42)
if isinstance(X, pd.DataFrame):
X = X.values
if isinstance(y, pd.Series):
y = y.values
_ = sss.get_n_splits(X, y)
Reports_Train = []
Reports_Test = []
CM_Train = []
CM_Test = []
for train_index, test_index in sss.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
_ = model.fit(X_train,y_train)
# Train
y_pred = model.predict(X_train)
R = pd.DataFrame(metrics.classification_report(y_train, y_pred, target_names=Labels, output_dict=True)).T
Reports_Train.append(R.values)
CM_Train.append(metrics.confusion_matrix(y_train, y_pred))
# Test
y_pred = model.predict(X_test)
R = pd.DataFrame(metrics.classification_report(y_test, y_pred, target_names=Labels, output_dict=True)).T
Reports_Test.append(R.values)
CM_Test.append(metrics.confusion_matrix(y_test, y_pred))
# Train
ALL = Reports_Train[0].ravel()
CM = CM_Train[0].ravel()
for i in range(1, len(Reports_Train)):
ALL = np.vstack((ALL, Reports_Train[i].ravel()))
CM = np.vstack((CM, CM_Train[i].ravel()))
Mean = pd.DataFrame(ALL.mean(axis = 0).reshape(R.shape), index = R.index, columns = R.columns)
STD = pd.DataFrame(ALL.std(axis = 0).reshape(R.shape), index = R.index, columns = R.columns)
Reports_Train = Mean.applymap(lambda x: ('%.4f' % x))+ ' ± ' +STD.applymap(lambda x: ('%.4f' % x))
CM_Train = CM.mean(axis = 0).reshape(CM_Train[0].shape).round(0).astype(int)
del ALL, Mean, STD
# Test
ALL = Reports_Test[0].ravel()
CM = CM_Test[0].ravel()
for i in range(1, len(Reports_Test)):
ALL = np.vstack((ALL, Reports_Test[i].ravel()))
CM = np.vstack((CM, CM_Test[i].ravel()))
Mean = pd.DataFrame(ALL.mean(axis = 0).reshape(R.shape), index = R.index, columns = R.columns)
STD = pd.DataFrame(ALL.std(axis = 0).reshape(R.shape), index = R.index, columns = R.columns)
Reports_Test = Mean.applymap(lambda x: ('%.4f' % x))+ ' ± ' +STD.applymap(lambda x: ('%.4f' % x))
CM_Test = CM.mean(axis = 0).reshape(CM_Test[0].shape).round(0).astype(int)
del ALL, Mean, STD
Reports_Train = Reports_Train.reset_index().rename(columns ={'index': 'Train Set (CV = % i)' % n_splits})
Reports_Test = Reports_Test.reset_index().rename(columns ={'index': 'Test Set (CV = % i)' % n_splits})
return Reports_Train, Reports_Test, CM_Train, CM_Test
def Confusion_Mat(CM_Train, CM_Test, n_splits = 10):
# Font
font = FontProperties()
font.set_weight('bold')
Titles = ['Train Set (CV = % i)' % n_splits, 'Test Set (CV = % i)' % n_splits]
CM = [CM_Train, CM_Test]
Cmap = ['Greens', 'YlGn','Blues', 'PuBu']
for i in range(2):
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
fig.suptitle(Titles[i], fontproperties=font, fontsize = 16)
_ = sns.heatmap(CM[i], annot=True, annot_kws={"size": 14}, cmap=Cmap[2*i], ax = ax[0],
linewidths = 0.2, cbar_kws={"shrink": 1})
_ = ax[0].set_title('Confusion Matrix');
_ = sns.heatmap(CM[i].astype('float') / CM[i].sum(axis=1)[:, np.newaxis],
annot=True, annot_kws={"size": 14}, cmap=Cmap[2*i+1], ax = ax[1],
linewidths = 0.2, vmin=0, vmax=1, cbar_kws={"shrink": 1})
_ = ax[1].set_title('Normalized Confusion Matrix');
for a in ax:
_ = a.set_xlabel('Predicted labels')
_ = a.set_ylabel('True labels');
_ = a.xaxis.set_ticklabels(Labels)
_ = a.yaxis.set_ticklabels(Labels)
_ = a.set_aspect(1)
Some of the metrics that we use here to mesure the accuracy: \begin{align} \text{Confusion Matrix} = \begin{bmatrix}T_p & F_p\\ F_n & T_n\end{bmatrix}. \end{align}
where $T_p$, $T_n$, $F_p$, and $F_n$ represent true positive, true negative, false positive, and false negative, respectively.
\begin{align} \text{Precision} &= \frac{T_{p}}{T_{p} + F_{p}},\\ \text{Recall} &= \frac{T_{p}}{T_{p} + F_{n}},\\ \text{F1} &= \frac{2 \times \text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}\\ \text{Balanced-Accuracy (bACC)} &= \frac{1}{2}\left( \frac{T_{p}}{T_{p} + F_{n}} + \frac{T_{n}}{T_{n} + F_{p}}\right ) \end{align}The accuracy can be a misleading metric for imbalanced data sets. In these cases, a balanced accuracy (bACC) [6] is recommended that normalizes true positive and true negative predictions by the number of positive and negative samples, respectively, and divides their sum by two.
Header('MLP with Default Parameters')
n_splits = 20
MLP= MLPClassifier()
print('Default Parameters = %s' % MLP.get_params(deep=True))
_ = MLP.fit(X_train, y_train)
Reports_Train, Reports_Test, CM_Train, CM_Test = Stratified_CV_Scoring(MLP, X = X, y = y, n_splits = n_splits)
display(Reports_Train.style.hide_index().set_properties(**{'background-color': 'HoneyDew', 'color': 'Black'}).\
set_properties(subset=['Train Set (CV = % i)' % n_splits], **{'background-color': 'SeaGreen', 'color': 'White'}))
display(Reports_Test.style.hide_index().set_properties(**{'background-color': 'Azure', 'color': 'Black'}).\
set_properties(subset=['Test Set (CV = % i)' % n_splits], **{'background-color': 'RoyalBlue', 'color': 'White'}))
Confusion_Mat(CM_Train, CM_Test, n_splits = n_splits)
Header('Train Set', C = 'Green')
tn, fp, fn, tp = CM_Train.ravel()
Precision = tp/(tp+fp)
Recall = tp/(tp + fn)
TPR = tp/(tp +fn)
TNR = tn/(tn +fp)
BA = (TPR + TNR)/2
print('Precision (Train) = %.2f' % Precision)
print('Recall (Train) = %.2f' % Recall)
print('TPR (Train) = %.2f' % TPR)
print('TNR (Train) = %.2f' % TNR)
print('Balanced Accuracy (Train) = %.2f' % BA)
Header('Test Set')
tn, fp, fn, tp = CM_Test.ravel()
Precision = tp/(tp+fp)
Recall = tp/(tp + fn)
TPR = tp/(tp +fn)
TNR = tn/(tn +fp)
BA = (TPR + TNR)/2
PPCR = (tp + fp)/(tp + fp + tn+ fn)
print('Precision (Test) = %.2f' % Precision)
print('Recall (Test) = %.2f' % Recall)
print('TPR (Test) = %.2f' % TPR)
print('TNR (Test) = %.2f' % TNR)
print('Balanced Accuracy (Test) = %.2f' % BA)
del tn, fp, fn, tp, Precision, Recall, TPR, TNR, BA
Line()
MLP with Default Parameters ======================================================================== Default Parameters = {'activation': 'relu', 'alpha': 0.0001, 'batch_size': 'auto', 'beta_1': 0.9, 'beta_2': 0.999, 'early_stopping': False, 'epsilon': 1e-08, 'hidden_layer_sizes': (100,), 'learning_rate': 'constant', 'learning_rate_init': 0.001, 'max_fun': 15000, 'max_iter': 200, 'momentum': 0.9, 'n_iter_no_change': 10, 'nesterovs_momentum': True, 'power_t': 0.5, 'random_state': None, 'shuffle': True, 'solver': 'adam', 'tol': 0.0001, 'validation_fraction': 0.1, 'verbose': False, 'warm_start': False}
| Train Set (CV = 20) | precision | recall | f1-score | support |
|---|---|---|---|---|
| Normal | 0.9999 ± 0.0001 | 1.0000 ± 0.0000 | 0.9999 ± 0.0000 | 19902.0000 ± 0.0000 |
| Fraud | 0.9957 ± 0.0137 | 0.9265 ± 0.0389 | 0.9592 ± 0.0201 | 34.0000 ± 0.0000 |
| accuracy | 0.9999 ± 0.0001 | 0.9999 ± 0.0001 | 0.9999 ± 0.0001 | 0.9999 ± 0.0001 |
| macro avg | 0.9978 ± 0.0068 | 0.9632 ± 0.0194 | 0.9796 ± 0.0101 | 19936.0000 ± 0.0000 |
| weighted avg | 0.9999 ± 0.0001 | 0.9999 ± 0.0001 | 0.9999 ± 0.0001 | 19936.0000 ± 0.0000 |
| Test Set (CV = 20) | precision | recall | f1-score | support |
|---|---|---|---|---|
| Normal | 0.9993 ± 0.0002 | 0.9999 ± 0.0002 | 0.9996 ± 0.0001 | 8530.0000 ± 0.0000 |
| Fraud | 0.9221 ± 0.0954 | 0.6267 ± 0.1143 | 0.7372 ± 0.0880 | 15.0000 ± 0.0000 |
| accuracy | 0.9992 ± 0.0002 | 0.9992 ± 0.0002 | 0.9992 ± 0.0002 | 0.9992 ± 0.0002 |
| macro avg | 0.9607 ± 0.0477 | 0.8133 ± 0.0571 | 0.8684 ± 0.0440 | 8545.0000 ± 0.0000 |
| weighted avg | 0.9992 ± 0.0002 | 0.9992 ± 0.0002 | 0.9992 ± 0.0003 | 8545.0000 ± 0.0000 |
Train Set ========================================================================================== Precision (Train) = 1.00 Recall (Train) = 0.94 TPR (Train) = 0.94 TNR (Train) = 1.00 Balanced Accuracy (Train) = 0.97 Test Set =========================================================================================== Precision (Test) = 0.90 Recall (Test) = 0.60 TPR (Test) = 0.60 TNR (Test) = 1.00 Balanced Accuracy (Test) = 0.80 ====================================================================================================
param_dist = dict(solver= ['lbfgs', 'sgd', 'adam'],
alpha= [10.0**x for x in np.arange(-1,-4,-1)],
learning_rate= ['constant', 'invscaling', 'adaptive'], max_iter = [200, 500, 1000])
Header('MLP with the Best Parameters')
grid = Best_Parm(model = MLP, param_dist = param_dist, Top = 20, H = 850, titleY =.96)
MLP with the Best Parameters =======================================================================
| Rank Test Score | Params | Train Score | Test Score | Fit Time |
|---|---|---|---|---|
| 1 | solver: adam, max_iter: 1000, learning_rate: adaptive, alpha: 0.001 | 9.81e-01 ± 3.83e-02 | 9.44e-01 ± 1.00e-01 | 3.88e+00 ± 7.70e-01 |
| 2 | solver: adam, max_iter: 500, learning_rate: adaptive, alpha: 0.01 | 9.86e-01 ± 3.50e-02 | 9.41e-01 ± 8.21e-02 | 5.61e+00 ± 1.29e+00 |
| 3 | solver: adam, max_iter: 500, learning_rate: constant, alpha: 0.01 | 9.92e-01 ± 1.38e-02 | 9.41e-01 ± 9.27e-02 | 5.29e+00 ± 1.22e+00 |
| 4 | solver: adam, max_iter: 500, learning_rate: adaptive, alpha: 0.001 | 9.91e-01 ± 1.61e-02 | 9.38e-01 ± 9.76e-02 | 4.52e+00 ± 1.25e+00 |
| 5 | solver: adam, max_iter: 500, learning_rate: invscaling, alpha: 0.001 | 9.83e-01 ± 3.00e-02 | 9.38e-01 ± 1.01e-01 | 4.53e+00 ± 1.38e+00 |
| 6 | solver: adam, max_iter: 200, learning_rate: adaptive, alpha: 0.01 | 9.94e-01 ± 1.24e-02 | 9.38e-01 ± 9.26e-02 | 5.34e+00 ± 1.69e+00 |
| 7 | solver: adam, max_iter: 1000, learning_rate: invscaling, alpha: 0.001 | 9.88e-01 ± 2.00e-02 | 9.35e-01 ± 8.59e-02 | 4.66e+00 ± 1.65e+00 |
| 8 | solver: adam, max_iter: 1000, learning_rate: constant, alpha: 0.001 | 9.84e-01 ± 2.99e-02 | 9.34e-01 ± 7.80e-02 | 4.61e+00 ± 1.44e+00 |
| 9 | solver: adam, max_iter: 200, learning_rate: constant, alpha: 0.001 | 9.91e-01 ± 1.66e-02 | 9.34e-01 ± 1.00e-01 | 4.66e+00 ± 1.26e+00 |
| 10 | solver: adam, max_iter: 1000, learning_rate: adaptive, alpha: 0.01 | 9.87e-01 ± 2.35e-02 | 9.31e-01 ± 8.60e-02 | 5.47e+00 ± 1.48e+00 |
| 11 | solver: adam, max_iter: 1000, learning_rate: constant, alpha: 0.01 | 9.77e-01 ± 3.97e-02 | 9.30e-01 ± 8.21e-02 | 5.62e+00 ± 1.53e+00 |
| 12 | solver: adam, max_iter: 1000, learning_rate: invscaling, alpha: 0.01 | 9.79e-01 ± 4.14e-02 | 9.29e-01 ± 9.40e-02 | 5.42e+00 ± 1.31e+00 |
| 13 | solver: adam, max_iter: 200, learning_rate: constant, alpha: 0.01 | 9.82e-01 ± 3.58e-02 | 9.27e-01 ± 9.02e-02 | 5.45e+00 ± 1.24e+00 |
| 14 | solver: adam, max_iter: 200, learning_rate: adaptive, alpha: 0.001 | 9.86e-01 ± 3.12e-02 | 9.25e-01 ± 1.03e-01 | 4.51e+00 ± 1.56e+00 |
| 15 | solver: adam, max_iter: 500, learning_rate: invscaling, alpha: 0.01 | 9.94e-01 ± 1.23e-02 | 9.24e-01 ± 9.76e-02 | 5.76e+00 ± 1.47e+00 |
| 16 | solver: adam, max_iter: 200, learning_rate: adaptive, alpha: 0.1 | 9.68e-01 ± 3.03e-02 | 9.23e-01 ± 9.58e-02 | 5.11e+00 ± 5.82e-01 |
| 17 | solver: adam, max_iter: 200, learning_rate: invscaling, alpha: 0.001 | 9.86e-01 ± 3.06e-02 | 9.20e-01 ± 9.23e-02 | 4.62e+00 ± 1.28e+00 |
| 18 | solver: adam, max_iter: 200, learning_rate: invscaling, alpha: 0.01 | 9.89e-01 ± 1.95e-02 | 9.20e-01 ± 9.99e-02 | 5.31e+00 ± 1.28e+00 |
| 19 | solver: adam, max_iter: 500, learning_rate: constant, alpha: 0.001 | 9.77e-01 ± 2.99e-02 | 9.16e-01 ± 9.75e-02 | 4.38e+00 ± 1.55e+00 |
| 20 | solver: adam, max_iter: 200, learning_rate: invscaling, alpha: 0.1 | 9.51e-01 ± 5.10e-02 | 9.12e-01 ± 1.07e-01 | 5.08e+00 ± 1.14e+00 |
Since we have identified the best parameters for our modeling, we train another model using these parameters.
Header('MLP with the Best Parameters')
MLP = MLPClassifier(**grid.best_params_)
print('Default Parameters = %s' % MLP.get_params(deep=True))
_ = MLP.fit(X_train, y_train)
Reports_Train, Reports_Test, CM_Train, CM_Test = Stratified_CV_Scoring(MLP, X = X, y = y, n_splits = 20)
display(Reports_Train.style.hide_index().set_properties(**{'background-color': 'HoneyDew', 'color': 'Black'}).\
set_properties(subset=['Train Set (CV = % i)' % n_splits], **{'background-color': 'DarkGreen', 'color': 'White'}))
display(Reports_Test.style.hide_index().set_properties(**{'background-color': 'Azure', 'color': 'Black'}).\
set_properties(subset=['Test Set (CV = % i)' % n_splits], **{'background-color': 'MediumBlue', 'color': 'White'}))
Confusion_Mat(CM_Train, CM_Test, n_splits = 20)
Header('Train Set', C = 'Green')
tn, fp, fn, tp = CM_Train.ravel()
Precision = tp/(tp+fp)
Recall = tp/(tp + fn)
TPR = tp/(tp +fn)
TNR = tn/(tn +fp)
BA = (TPR + TNR)/2
print('Precision (Train) = %.2f' % Precision)
print('Recall (Train) = %.2f' % Recall)
print('TPR (Train) = %.2f' % TPR)
print('TNR (Train) = %.2f' % TNR)
print('Balanced Accuracy (Train) = %.2f' % BA)
Header('Test Set')
tn, fp, fn, tp = CM_Test.ravel()
Precision = tp/(tp+fp)
Recall = tp/(tp + fn)
TPR = tp/(tp +fn)
TNR = tn/(tn +fp)
BA = (TPR + TNR)/2
PPCR = (tp + fp)/(tp + fp + tn+ fn)
print('Precision (Test) = %.2f' % Precision)
print('Recall (Test) = %.2f' % Recall)
print('TPR (Test) = %.2f' % TPR)
print('TNR (Test) = %.2f' % TNR)
print('Balanced Accuracy (Test) = %.2f' % BA)
del tn, fp, fn, tp, Precision, Recall, TPR, TNR, BA
Line()
MLP with the Best Parameters ======================================================================= Default Parameters = {'activation': 'relu', 'alpha': 0.001, 'batch_size': 'auto', 'beta_1': 0.9, 'beta_2': 0.999, 'early_stopping': False, 'epsilon': 1e-08, 'hidden_layer_sizes': (100,), 'learning_rate': 'adaptive', 'learning_rate_init': 0.001, 'max_fun': 15000, 'max_iter': 1000, 'momentum': 0.9, 'n_iter_no_change': 10, 'nesterovs_momentum': True, 'power_t': 0.5, 'random_state': None, 'shuffle': True, 'solver': 'adam', 'tol': 0.0001, 'validation_fraction': 0.1, 'verbose': False, 'warm_start': False}
| Train Set (CV = 20) | precision | recall | f1-score | support |
|---|---|---|---|---|
| Normal | 0.9998 ± 0.0001 | 1.0000 ± 0.0000 | 0.9999 ± 0.0000 | 19902.0000 ± 0.0000 |
| Fraud | 0.9926 ± 0.0157 | 0.9044 ± 0.0371 | 0.9458 ± 0.0174 | 34.0000 ± 0.0000 |
| accuracy | 0.9998 ± 0.0001 | 0.9998 ± 0.0001 | 0.9998 ± 0.0001 | 0.9998 ± 0.0001 |
| macro avg | 0.9962 ± 0.0078 | 0.9522 ± 0.0185 | 0.9729 ± 0.0087 | 19936.0000 ± 0.0000 |
| weighted avg | 0.9998 ± 0.0001 | 0.9998 ± 0.0001 | 0.9998 ± 0.0001 | 19936.0000 ± 0.0000 |
| Test Set (CV = 20) | precision | recall | f1-score | support |
|---|---|---|---|---|
| Normal | 0.9994 ± 0.0002 | 0.9999 ± 0.0001 | 0.9996 ± 0.0001 | 8530.0000 ± 0.0000 |
| Fraud | 0.9305 ± 0.0984 | 0.6400 ± 0.1306 | 0.7483 ± 0.1007 | 15.0000 ± 0.0000 |
| accuracy | 0.9993 ± 0.0003 | 0.9993 ± 0.0003 | 0.9993 ± 0.0003 | 0.9993 ± 0.0003 |
| macro avg | 0.9649 ± 0.0492 | 0.8200 ± 0.0653 | 0.8740 ± 0.0504 | 8545.0000 ± 0.0000 |
| weighted avg | 0.9992 ± 0.0003 | 0.9993 ± 0.0003 | 0.9992 ± 0.0003 | 8545.0000 ± 0.0000 |
Train Set ========================================================================================== Precision (Train) = 1.00 Recall (Train) = 0.91 TPR (Train) = 0.91 TNR (Train) = 1.00 Balanced Accuracy (Train) = 0.96 Test Set =========================================================================================== Precision (Test) = 0.91 Recall (Test) = 0.67 TPR (Test) = 0.67 TNR (Test) = 1.00 Balanced Accuracy (Test) = 0.83 ====================================================================================================
In the next article, we try to improve these results using PyTorch MLP.